﻿using Api.Shared.Model.Common;
using Api.Shared.Model.Impl;
using Api.Shared.Model.Olaiya;
using Api.Shared.Sugar;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using KxApp.Utils;
using Microsoft.Extensions.DependencyInjection;
using SqlSugar;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;

namespace KxApp.ViewModels
{
    [ExposedService(Lifetime.Singleton)]
    public partial class TableViewModel : ObservableObject
    {
        private readonly ISugarClientService helper;

        public TableViewModel(
            [FromKeyedServices(nameof(SqlName.sqliteST))] ISugarClientService helper
        )
        {
            this.helper = helper;

            //GotoPage(1);


        }

        [ObservableProperty]
        private ObservableCollection<Person> students = new();

        [ObservableProperty]
        private int maxPageCount;

        [ObservableProperty]
        private int id = 1;

        [ObservableProperty]
        private int age = 2;

        [ObservableProperty]
        private DateTime myStartDateTime;

        [ObservableProperty]
        private DateTime myEndDateTime;

        private const int pageSize = 20;
        private int totalNumber;

        private int pageIndex = 1;

        /// <summary>
        /// 点击按钮翻页
        /// </summary>
        public int PageIndex
        {
            get { return pageIndex; }
            set
            {
                bool a = SetProperty(ref pageIndex, value);
                if (a)
                {
                    GotoPage(value);
                }
            }
        }

        /// <summary>
        /// 递归函数，翻页
        /// </summary>
        /// <param name="pageNum">当前页数，控件传进来/查询传进来</param>
        private async void GotoPage(int pageIndex)
        {
            //this.PageNum = pageNum;
            //PageModel pageModel = new()
            //{
            //    PageIndex = pageNum,
            //    PageSize = pageSize,
            //    TotalCount = totalNumber
            //};
            //var a = await studentsRes.GetPageListAsync(x => true, pageModel);

            // var cc =  sugar.Db.Queryable<TcpMessage>().GroupBy(x => x.Message).Count();
            //vue 分页仅仅 需要总数量 和 当前页. 而handycontrol 需要 总页数(用总数量算出来) 和当前页. 都不需要sqlsugar的 totalpage 总页数
            RefAsync<int> total = 0;


            if (MyStartDateTime > MyEndDateTime || MyStartDateTime == MyEndDateTime)
            {
                var aa = await helper.Db.Queryable<OLTask>().CountAsync();

                var a = await helper.Db.Queryable<OLTask>().Includes(x => x.MaterialList).ToPageListAsync(pageIndex, pageSize, total);
                //用groupby后 total变的不准, 要自己算
                MaxPageCount = (int)Math.Ceiling((double)aa / pageSize);
                ;
                OLTasks = [.. a];
            }
            else
            {
                var aa = await helper.Db.Queryable<OLTask>()
                    .Where(x=>x.CreateTime > MyStartDateTime && x.CreateTime < MyEndDateTime)
                    .CountAsync();

                var a = await helper.Db.Queryable<OLTask>()
                    .Where(x => x.CreateTime > MyStartDateTime && x.CreateTime < MyEndDateTime)
                    .Includes(x => x.MaterialList).ToPageListAsync(pageIndex, pageSize, total);
                //用groupby后 total变的不准, 要自己算
                MaxPageCount = (int)Math.Ceiling((double)aa / pageSize);
                ;
                OLTasks = [.. a];
            }
        }

        public void MyMouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBox textBox = sender as TextBox;
            if (textBox != null)
            {
                textBox.SelectAll();
            }
        }

        [RelayCommand]
        public async Task UpdateDzt(OLTask oLTask)
        {
            MessageBoxResult result = MessageBox.Show(
                "你确定要执行此操作吗?",
                "确认",
                MessageBoxButton.YesNo,
                MessageBoxImage.Question
            );

            if (result == MessageBoxResult.Yes)
            {
                try
                {
                    var count = await helper.Db.Updateable(oLTask).ExecuteCommandAsync();
                    if (count > 0)
                    {
                        net8Wpf.Core.Diag.PopupBox.Show("修改成功!", null, 2, "蓝");
                    }
                }
                catch (Exception ex)
                {
                    net8Wpf.Core.Diag.PopupBox.Show($"修改失败!{ex.Message}", null, 2, "红");
                }
            }
            else { }
        }

        [RelayCommand]
        public async Task DeleteDzt(OLTask oLTask)
        {
            //MessageBoxResult result = MessageBox.Show(
            //    "你确定要执行此操作吗?",
            //    "确认",
            //    MessageBoxButton.YesNo,
            //    MessageBoxImage.Question
            //);

            //if (result == MessageBoxResult.Yes)
            //{
            //    var count = await helper.Db.Deleteable(oLTask).ExecuteCommandAsync();
            //    if (count > 0)
            //    {
            //        net8Wpf.Core.Diag.PopupBox.Show("删除成功!", null, 2, "红");
            //    }
            //}
            //else { }
        }


        [RelayCommand]
        public async Task Complete()
        {
            if (OLTasks.Count == 0)
            {
                return;
            }
            else
            {
                foreach (var item in OLTasks)
                {
                    item.IsCompleted = true;
                }
                try
                {
                    var count = await helper.Db.Updateable(OLTasks).ExecuteCommandAsync();
                    if (count > 0)
                    {
                        net8Wpf.Core.Diag.PopupBox.Show("修改成功!", null, 2, "蓝");
                    }
                }
                catch (Exception ex)
                {
                    net8Wpf.Core.Diag.PopupBox.Show($"修改失败!{ex.Message}", null, 2, "红");
                }
            }
        }

        [RelayCommand]
        public void AskFor(Person person) { }

        [RelayCommand]
        public void DgvCmd()
        {

        }

        [RelayCommand]
        public async Task Query()
        {
            RefAsync<int> total = 0;


            if (MyStartDateTime > MyEndDateTime || MyStartDateTime == MyEndDateTime)
            {
                var aa = await helper.Db.Queryable<OLTask>().CountAsync();

                var a = await helper.Db.Queryable<OLTask>().Includes(x => x.MaterialList).ToPageListAsync(pageIndex, pageSize, total);
                //用groupby后 total变的不准, 要自己算
                MaxPageCount = (int)Math.Ceiling((double)aa / pageSize);
                ;
                OLTasks = [.. a];
            }
            else
            {
                var aa = await helper.Db.Queryable<OLTask>()
                    .Where(x => x.CreateTime > MyStartDateTime && x.CreateTime < MyEndDateTime)
                    .CountAsync();

                var a = await helper.Db.Queryable<OLTask>()
                    .Where(x => x.CreateTime > MyStartDateTime && x.CreateTime < MyEndDateTime)
                    .Includes(x => x.MaterialList).ToPageListAsync(pageIndex, pageSize, total);
                //用groupby后 total变的不准, 要自己算
                MaxPageCount = (int)Math.Ceiling((double)aa / pageSize);
                ;
                OLTasks = [.. a];
            }
        }

        private DispatcherTimer scrollTimer;
        private ScrollViewer scrollViewer;
        private double scrollHeight;
        private bool isScrollingDown = true;
        private const double ScrollStep = 1.0; // 每次滚动的像素
        private const int ScrollInterval = 50; // 滚动间隔(毫秒)

        #region 表格2


        [ObservableProperty]
        private List<OLTask> oLTasks = new();

        [ObservableProperty]
        private int detailInex;

        [RelayCommand]
        public void Detail(DataGrid dataGrid)
        {
            DataGridRow dataGridRow = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(DetailInex);
            if (dataGridRow.DetailsVisibility == System.Windows.Visibility.Visible)
            {
                dataGridRow.DetailsVisibility = System.Windows.Visibility.Collapsed;
            }
            else
            {
                dataGridRow.DetailsVisibility = System.Windows.Visibility.Visible;
            }
        }

        #endregion
    }
}
